package com.haste.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.cloud.commons.util.IdUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.UUID;


/**
 * @ClassName:PaymentService
 * @Description:
 * @Author:Haste
 * @Date:2021/2/8 9:24
 */
@Service
public class PaymentService {
    public String paymentInfo(Integer id){
        return "线程池："+Thread.currentThread().getName()+" paymentInfo:"+id;
    }

    /*@HystrixCommand(fallbackMethod = "reminder",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
    })*///服务降级,没有指定的异常依然走到了备选方法,当配置了全局fallback之后，这里不注掉的话，如果访问的是这里，那么走的是这里的
    public String paymentInfoTimeout(Integer id){
        /*int time = 1;
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        int a = 10/0;
        return "线程池："+Thread.currentThread().getName()+" paymentInfo:"+id+"耗时"+"钟";
    }

    public String reminder(Integer id){//参数也是寻找的依据
        return "系统繁忙，稍后再试！";
    }

    /**
     * @author:Haste
     * @description:熔断
     * @date:2021/2/8 13:32
     * @param:[id]
     * @return:java.lang.String
     */
    @HystrixCommand(fallbackMethod = "paymentBreakerFallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//10秒钟之内10次访问，失败60次后，时间窗口期（时间范围）
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60") //失败多少次？（60%？）后跳匝
            //服务熔断-->服务降级-->服务恢复
    })
    public String paymentBreaker(@PathVariable("id") Integer id){
        if (id < 0){
            throw new RuntimeException("id 不能为负数");
        }
        String serial = UUID.randomUUID().toString();
        return serial;
    }

    public String paymentBreakerFallback(@PathVariable("id") Integer id){
        return "id 不能为负数，请重新输入";
    }
}
